class compiler {
	//compiler-compile
	constructor(vm) {
		this.el = vm.$el
		this.vm = vm
		this.compile(this.el)
	}
	//编译模板
	compile(el) {
		let childnodes = el.childNodes
		Array.from(childnodes).forEach(node => {
			if (this.istextnode(node)) {
				this.compiletext(node)
			} else if (this.iselementnode(node)) {
				this.compileelement(node)
			}

			if (node.childNodes && node.childNodes.length) {
				this.compile(node)
			}
		})

	}
	//指令处理
	compileelement(node) {
		Array.from(node.attributes).forEach(attr => {
			let attrname = attr.name
			if (this.isdirective(attrname)) {
				attrname = attrname.substr(2)
				let key = attr.value
				if(attrname.split(':')[0] == 'on'){
					this.ons(node, key, attrname,this.vm)
					return
				}
				this.updater(node, key, attrname)
			}
		})
	}
	updater(node, key, attrname) {
		let updatefn = this[attrname + 'updater']
		updatefn && updatefn(node, this.vm[key], this.vm, attrname)
	}
	//v-text
	textupdater(node, value) {
		node.textContent = value
	}
	//v-model
	modelupdater(node, value) {
		node.value = value
	}
	htmlupdater(node, value) {
		node.innerHTML = value
	}
	ons(node, value, attrname,vm) {
		let key = attrname.split(':')[1]
		let ons = this[key + 'event']
		ons && ons(node,value,vm);
	}
	
	clickevent(node,value,vm){
		node.onclick = vm.$options.methods[value]
	}
	//插值表达式处理
	compiletext(node) {
		/* console.dir(node) */
		let reg = /\{\{(.+?)\}\}/;
		let value = node.textContent
		if (reg.test(value)) {
			let key = RegExp.$1.trim()
			node.textContent = value.replace(reg, this.vm[key])
		}
	}
	//判断是否为指令
	isdirective(attrname) {
		return attrname.startsWith('v-')
	}
	//判断是否是文本节点
	istextnode(node) {
		return node.nodeType === 3
	}
	//判断是否是元素节点
	iselementnode(node) {
		return node.nodeType === 1
	}
}
